import type { CartItem } from '@/types/cart'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export const useCartStore = defineStore(
  'cart',
  () => {
    const cart = ref<CartItem[]>([])
    // 存储购物车数据
    const setCart = (val: CartItem) => {
      const find = cart.value.find((item) => item._id === val._id)
      if (find) {
        find.buy_num += val.buy_num
        find.buy_num = find.buy_num > 10 ? 10 : find.buy_num
      } else {
        cart.value = [val, ...cart.value]
      }
    }
    // 删除购物车数据
    const deleteCart = (id: string) => {
      cart.value = cart.value.filter((item) => item._id !== id)
    }
    const changeCount = (id: string, num: number) => {
      cart.value.find((item) => item._id === id)!.buy_num = num
    }
    // 修改商品选中状态
    const changeChecked = (id: string) => {
      const find = cart.value.find((item) => item._id === id)
      find!.selected = !find!.selected
    }
    // 全选按钮是否选中
    const isAllChecked = computed(() => {
      return cart.value.every((item) => item.selected)
    })
    // 全选按钮点击事件
    const checkAll = () => {
      isAllChecked.value
        ? cart.value.forEach((item) => (item.selected = false))
        : cart.value.forEach((item) => (item.selected = true))
    }
    // 购物车总数量
    const totalNum = computed(() => {
      return cart.value.filter((item) => item.selected).reduce((acc, cur) => acc + cur.buy_num, 0)
    })
    // 购物车总价格
    const totalPrice = computed(() => {
      return cart.value
        .filter((item) => item.selected)
        .reduce((acc, cur) => acc + (cur.price / 100) * cur.buy_num, 0)
    })
    const discountAmount = computed(() => {
      return (totalPrice.value * 0.75).toFixed(2)
    })
    const discount = computed(() => {
      return (totalPrice.value * 0.25).toFixed(2)
    })
    return {
      cart,
      setCart,
      deleteCart,
      changeCount,
      changeChecked,
      isAllChecked,
      checkAll,
      totalNum,
      discountAmount,
      discount,
    }
  },
  {
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          return uni.setStorageSync(key, value)
        },
      },
    },
  },
)
